var __parentNode = window.parent.document;

function $childNode(name) {
    return window.frames[name]
}

function $container(){
    return $(__parentNode).find('#content-main')
}

function calcSuitableHeight(widget, minHeight, bottomMargin, tableExtend){
    if(!bottomMargin){
        bottomMargin = 100;
    }
    if(!minHeight){
        minHeight = 450;
    }

    if(!tableExtend){
        tableExtend = 0;
    }

    var $widget = (widget instanceof jQuery) ? widget : $(widget);
    var _maxHeight = $container().height();
    var _height = _maxHeight - $widget.offset().top - bottomMargin + tableExtend;
    return _height < minHeight ? minHeight : _height;
}

function calcTableHeight(widget, minHeight, bottomMargin, tableExtend){
    return calcSuitableHeight(widget, minHeight, bottomMargin, tableExtend?tableExtend:41);
}

// tooltips
$('.tooltip-demo').tooltip({
    selector: "[data-toggle=tooltip]",
    container: "body"
});

// 使用animation.css修改Bootstrap Modal
$('.modal').appendTo("body");

$("[data-toggle=popover]").popover();

//折叠ibox
$('.collapse-link').click(function () {
    var ibox = $(this).closest('div.ibox');
    var button = $(this).find('i');
    var content = ibox.find('div.ibox-content');
    content.slideToggle(200);
    button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
    ibox.toggleClass('').toggleClass('border-bottom');
    setTimeout(function () {
        ibox.resize();
        ibox.find('[id^=map-]').resize();
    }, 50);
});

//关闭ibox
$('.close-link').click(function () {
    var content = $(this).closest('div.ibox');
    content.remove();
});

//判断当前页面是否在iframe中
if (top == this) {
    var gohome = '<div class="gohome"><a class="animated bounceInUp" href="index.html?v=4.0" title="返回首页"><i class="fa fa-home"></i></a></div>';
    $('body').append(gohome);
}

//animation.css
function animationHover(element, animation) {
    element = $(element);
    element.hover(
        function () {
            element.addClass('animated ' + animation);
        },
        function () {
            //动画完成之前移除class
            window.setTimeout(function () {
                element.removeClass('animated ' + animation);
            }, 2000);
        });
}

//拖动面板
function WinMove() {
    var element = "[class*=col]";
    var handle = ".ibox-title";
    var connect = "[class*=col]";
    $(element).sortable({
            handle: handle,
            connectWith: connect,
            tolerance: 'pointer',
            forcePlaceholderSize: true,
            opacity: 0.8,
        })
        .disableSelection();
};

var _FormKit_ = function(){

    /**
     * 根据控件和前缀获取字段名字，绑定表单数据时使用
     * @param $widget 对应控件
     * @param prefix 前缀
     * @returns {*} 字段名称
     */
    function getFieldName($widget, prefix) {
        var name = $widget.attr("name");
        if (name && prefix) {
            var prefixLength = prefix.length + 1;
            if (name.substring(0, prefixLength) == prefix + '.') {
                return name.substring(prefixLength);
            }
        } else {
            return name;
        }
        return false;
    }

    /**
     * 绑定表单数据
     * @param selector 表单选择器或jQuery对象
     * @param data  数据对象
     * @param prefix 表单name中的前缀
     * @param readOnly 是否只读
     */
    function bindData(selector, data, prefix, readOnly){
        //根据选择器获得表单对象
        var $form = (selector instanceof jQuery)?selector:$(selector);
        //设置输入框,复选框,单选框input类型的数据
        $form.find("input[data-bind]").each(function (i, input) {
            var $input = $(input);
            var inputType = $input.attr("type");
            var fieldName = getFieldName($input, prefix);
            var fieldValue = data?data[fieldName]:null;
            if ("checkbox" == inputType || "radio" == inputType) {
                fieldValue && fieldValue == $input.val() ? $input.attr('checked', 'checked') : $input.removeAttr('checked');
            } else if ("text" == inputType || "hidden" == inputType) {
                fieldValue ? $input.val(fieldValue) : $input.val('');
            }
            if(readOnly){
                $input.attr("readonly","readonly");
            }else{
                $input.removeAttr("readonly");
            }
        });
        //设置文本域textarea类型的数据
        $form.find("textarea[data-bind]").each(function (i, textarea) {
            var $textarea = $(textarea)
            var fieldName = getFieldName($textarea, prefix);
            var fieldValue = data?data[fieldName]:null;
            fieldValue ? $textarea.val(fieldValue) : $textarea.val('');
            if(readOnly){
                $textarea.attr("readonly","readonly");
            }else{
                $textarea.removeAttr("readonly");
            }
        });
        //设置下拉选择select类型的数据
        $form.find("select[data-bind]").each(function (i, select) {
            var $select = $(select)
            var fieldName = getFieldName($select, prefix);
            var fieldValue = data?data[fieldName]:null;
            if (fieldValue) {
                $select.val(fieldValue);
            }

            if(readOnly){
                $select.attr("disabled","disabled");
            }else{
                $select.removeAttr("disabled");
            }
        });
    }

    /**
     * 根据flag设置文本编辑控件是否可修改
     * @param selector 表单的选择器或jQuery对象
     * @param flag true:只读,false:可修改
     */
    function setReadOnly(selector, flag) {
        var $form = (selector instanceof jQuery)?selector:$(selector);
        $form.find('input').each(function (i, input) {
            flag ? $(input).attr("readonly", "readonly") : $(input).removeAttr("readonly");
        });
        $form.find('textarea').each(function (i, textarea) {
            flag ? $(textarea).attr("readonly", "readonly") : $(textarea).removeAttr("readonly");
        });
        $form.find('select').each(function (i, textarea) {
            flag ? $(textarea).attr("disabled", "disabled") : $(textarea).removeAttr("disabled");
        });
    }

    return {
        "bindData" : bindData,
        "setReadOnly" : setReadOnly
    }
}();

var _GetDictKit = function(){

    var __dictMap = {};

    if(arguments.length > 0){
        var _codes = [];
        for (var i=0, l=arguments.length;i<l;i++){
            _codes.push(arguments[i]);
        }
        $.ajax({
            url: _CTX_ + '/core/dictionary/findByParentCodes',
            type: 'POST',
            data: $.param({"codes": _codes}, true),
            async: false,
            cache: true,
            dataType: 'json',
            success: function (ret) {
                if (ret.state == 'ok') {
                    __dictMap = ret.data;
                } else {
                    alert(ret.msg);
                }
            }
        });
    }

    function _getDictByKey(key){
        if(__dictMap.hasOwnProperty(key)){
            return __dictMap[key];
        }else{
            $.ajax({
                url: _CTX_ + '/core/dictionary/findByParentCodes',
                type: 'POST',
                data: $.param({"codes": [key]}, true),
                async: false,
                cache: true,
                dataType: 'json',
                success: function (ret) {
                    if (ret.state == 'ok') {
                        var _temp = {};
                        var _data = ret.data;
                        for(var _index in _data){
                            _temp[_data[_index]["code"]]=_data[_index]["label"];
                        }
                        __dictMap[key] = _temp;
                    } else {
                        alert(ret.msg);
                    }
                }
            });
        }
    }

    function _getLabel(key,code){
        if(__dictMap.hasOwnProperty(key)){
            return __dictMap[key][code];
        }else{
            var _dict = _getDictByKey(key);
            return _dict[code];
        }
    }

    function _initSelect(selector,key,selectCode){
        var $selector = (selector instanceof jQuery)?selector:$(selector);
        var _dict = _getDictByKey(key);
        $selector.empty();
        for(var _code in _dict){
            var $option = $('<option value="' + _code + '">' + _dict[_code] + '</option>');
            $selector.append($option);
        }
        if(selectCode){
            $selector.val(selectCode);
        }
    }

    return {
        getLabel : function(key, code){
            return _getLabel(key,code);
        },
        getDict : function (key) {
            return _getDictByKey(key);
        },
        initSelect : function(selector,key,selectCode){
            return _initSelect(selector,key,selectCode);
        }
    }

};


var _GetDatasetKit = function(){

    var __dataSetMap = {};

    if(arguments.length > 0){
        var _codes = [];

        for (var i=0, l=arguments.length;i<l;i++){
            _codes.push(arguments[i]);
        }

        $.ajax({
            url: _CTX_ + '/core/dataset/findByCodes',
            type: 'POST',
            data: $.param({"codes": _codes}, true),
            async: false,
            cache: true,
            dataType: 'json',
            success: function (ret) {
                if (ret.state == 'ok') {
                    __dataSetMap = ret.data;
                } else {
                    alert(ret.msg);
                }
            }
        });
    }

    function _getDataByKey(key){
        if(__dataSetMap.hasOwnProperty(key)){
            return __dataSetMap[key];
        }else{
            $.ajax({
                url: _CTX_ + '/core/dataset/findByCodes',
                type: 'POST',
                data: $.param({"codes": [key]}, true),
                async: false,
                cache: true,
                dataType: 'json',
                success: function (ret) {
                    if (ret.state == 'ok') {
                        var _temp = {};
                        var _data = ret.data;
                        for(var _index in _data){
                            _temp[_data[_index]["code"]]=_data[_index]["label"];
                        }
                        __dataSetMap[key] = _temp;
                    } else {
                        alert(ret.msg);
                    }
                }
            });
        }
    }

    function _getLabel(key,code){
        if(__dataSetMap.hasOwnProperty(key)){
            return __dataSetMap[key][code];
        }else{
            var _dict = _getDataByKey(key);
            return _dict[code];
        }
    }

    function _initSelect(selector,key,selectCode){
        var $selector = (selector instanceof jQuery)?selector:$(selector);
        var _dict = _getDataByKey(key);
        $selector.empty();
        for(var _code in _dict){
            var $option = $('<option value="' + _code + '">' + _dict[_code] + '</option>');
            $selector.append($option);
        }
        if(selectCode){
            $selector.val(selectCode);
        }
    }

    return {
        getLabel : function(key, code){
            return _getLabel(key,code);
        },
        getData : function (key) {
            return _getDataByKey(key);
        },
        initSelect : function(selector,key,selectCode){
            return _initSelect(selector,key,selectCode);
        }
    }

};